/*
 * This class converts a password (string) to a sha1 and md5 hashed password
 */
package classes;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Achie
 */
public class Password {

    private String hashedPassword; //hashed password

    public Password(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        setHashedPassword(password); //execute hasher
    }

    public String getHashedPassword() {
        return hashedPassword;
    }

    /*
     * startup method
     */
    public void setHashedPassword(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        //make md5
        byte[] md5byte = createMD5byte(password);
        hashedPassword = bytesToString(md5byte);
        //make sha1
        byte[] sha1byte = createSHAbyte(hashedPassword);
        hashedPassword = bytesToStringForSha(sha1byte);
        this.hashedPassword = hashedPassword;
    }

    //--------------------------------------------------------------------------
    //MD5 encryption
    //--------------------------------------------------------------------------
    public byte[] createMD5byte(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(password.getBytes());
        byte[] bytepassword = password.getBytes();
        byte[] hashed = md.digest(bytepassword);
        return hashed;
    }

    public String bytesToString(byte[] bytes) {
        System.out.println("bytes to string");
        StringBuilder string = new StringBuilder();
        for (byte b : bytes) {
            String hexString = Integer.toHexString(0x00FF & b);
            string.append(hexString.length() == 1 ? "0" + hexString : hexString);
        }
        return string.toString();
    }

    //--------------------------------------------------------------------------
    //SHA1 encryption
    //--------------------------------------------------------------------------
    public byte[] createSHAbyte(String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA1");
        md.update(password.getBytes());
        byte[] bytepassword = password.getBytes();
        byte[] hashed = md.digest(bytepassword);
        return hashed;
    }

    public String bytesToStringForSha(byte[] bytes) {
        System.out.println("bytes to string");
        StringBuilder string = new StringBuilder();
        for (byte b : bytes) {
            String hexString = Integer.toHexString(0x00FF & b);
            string.append(hexString.length() == 1 ? "0" + hexString : hexString);
        }
        return string.toString();
    }
}
